package com.fan.cachewebview.net

import android.content.Context
import okhttp3.Cache
import okhttp3.OkHttpClient
import org.apache.http.conn.ssl.AllowAllHostnameVerifier
import java.io.File
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import javax.net.ssl.KeyManager
import javax.net.ssl.SSLContext

/**
 * @description Okhttp工厂类
 * @date: 2022/2/22 17:32
 * @author: fan
 */
class OkHttpFactory private constructor(context: Context) {
    private var mClient: OkHttpClient? = null

    @Suppress("DEPRECATION")
    private fun createOkHttpClient(context: Context) {
        val dir = context.cacheDir.toString() + File.separator + CACHE_OKHTTP_DIR_NAME

        try {
            val trustManager = TrustAllCerts()
            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null as Array<KeyManager?>?, arrayOf(trustManager), SecureRandom())
            val sslSocketFactory = sslContext.socketFactory
            mClient = OkHttpClient.Builder()
                .cache(
                    Cache(
                        File(dir),
                        OKHTTP_CACHE_SIZE.toLong()
                    )
                )
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(
                    20,
                    TimeUnit.SECONDS
                )
                .hostnameVerifier(AllowAllHostnameVerifier())
                .sslSocketFactory(sslSocketFactory, trustManager)
                // 不允许自动重定向
                .followSslRedirects(false)
                .followRedirects(false)
                .build()

        } catch (e: Exception) {
            e.printStackTrace()
        }

    }



    companion object {
        private const val CACHE_OKHTTP_DIR_NAME = "okhttp_cache_webview"

        // 默认 100M 缓存
        private const val OKHTTP_CACHE_SIZE = 100 * 1024 * 1024

        @Volatile
        private var sInstance: OkHttpFactory? = null
        private fun getInstance(context: Context): OkHttpFactory? {
            if (sInstance == null) {
                synchronized(OkHttpFactory::class.java) {
                    if (sInstance == null) {
                        sInstance = OkHttpFactory(context)
                    }
                }
            }
            return sInstance
        }

        operator fun get(context: Context): OkHttpClient? {
            return getInstance(context)!!.mClient
        }
    }

    init {
        createOkHttpClient(context)
    }
}
